<template>
    <div class="packageLink">
        <div class="btn_box">
            <el-button icon="el-icon-plus" type="primary" @click="onAdd()">
                {{ $t('add.add54') }}
            </el-button>
        </div>
        <el-table :data="tableData" style="width: 100%" :height="tableH" highlight-current-row current-row-key="id">
            <el-table-column prop="clientType" align="center" :label="$t('versionManagement.version10')">
                <template #default="scope">{{ getClientTypeLabel(scope.row.clientType) }}</template>
            </el-table-column>
            <el-table-column prop="versionType" align="center" :label="$t('versionManagement.version39')">
            </el-table-column>
            <el-table-column prop="url" align="center" :label="$t('versionManagement.version40')">
                <template #default="scope">
                    <span ref="copy_download_link" class="copy-download-link"
                        :data-clipboard-text="$config.downloadUrl + scope.row.url">{{ $config.downloadUrl +
                            scope.row.url }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="isDelete" align="center" :label="$t('versionManagement.version41')">
                <template #default="scope">
                    <span v-show="scope.row.isDelete === '-1'">{{ $t('versionManagement.version46') }}</span>
                    <span v-show="scope.row.isDelete === '1'">{{ $t('versionManagement.version47') }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="uploadTime" align="center" :label="$t('add.add134')">
            </el-table-column>
            <el-table-column prop="updateTime" align="center" :label="$t('versionLogManagement.version06')">
            </el-table-column>
            <el-table-column :label="$t('versionManagement.version26')" align="center" width="200">
                <template #default="scope">
                    <el-button type="text" class="copy_box" @click="toAction('1', scope.row)">{{
                        $t('versionManagement.version42')
                        }}</el-button>
                    <el-button type="text" @click="toAction('2', scope.row)" v-show="scope.row.isDelete === '1'">{{
                        $t('versionManagement.version43') }}</el-button>
                    <el-button type="text" @click="toAction('3', scope.row)" v-show="scope.row.isDelete === '-1'">{{
                        $t('versionManagement.version44') }}</el-button>
                </template>
            </el-table-column>

            <el-table-column :label="$t('versionManagement.version45')" align="center">
                <template #default="scope">
                    <el-button type="text" @click="toAction('4', scope.row)">{{ $t('add.add045') }}</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background :current-page="pageable.page" :page-size="pageable.pageSize"
            :page-sizes="[10, 20, 50, 100]" :total="pageable.total" layout="total, sizes, prev, pager, next, jumper"
            @size-change="onPageSizeChange" @current-change="onPageChange" />



        <waterTable ref="waterTable" @closeWaterTable="
            isShowWaterTable = false;
        tableH = 570;
        " v-show="isShowWaterTable" :id="currRow.id"></waterTable>

        <!-- 添加弹框 -->
        <el-dialog :title="$t('add.add54')" :visible.sync="addDialogVisible" :close-on-click-modal="false" width="30%"
            @close="toMainCancel">
            <el-form :model="addRuleForm" :rules="addRules" ref="addRuleForm" label-width="120px">
                <el-form-item :label="$t('versionManagement.version10')" prop="clientType">
                    <el-select v-model="addRuleForm.clientType" :placeholder="$t('versionManagement.version15')">
                        <el-option v-for="option in clientTypeOptions" :key="option.value" :value="option.value"
                            :label="option.label" />
                    </el-select>
                </el-form-item>

                <el-form-item :label="$t('versionManagement.version11')" prop="version">
                    <el-input v-model="addRuleForm.version" :placeholder="$t('versionManagement.version11')"></el-input>
                </el-form-item>

                <el-form-item :label="$t('versionManagement.version40')" prop="url">
                    <el-input v-model="addRuleForm.url" :placeholder="$t('versionManagement.version57')"></el-input>
                </el-form-item>

                <el-form-item :label="$t('versionManagement.version39')" prop="versionType">
                    <el-input v-model="addRuleForm.versionType"
                        :placeholder="$t('versionManagement.version58')"></el-input>
                </el-form-item>


            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="toMainCancel()">
                    {{ $t('add.add31') }}
                </el-button>
                <el-button type="primary" @click="toMainSubmit()">
                    {{ $t('add.add30') }}
                </el-button>
            </span>
        </el-dialog>
        <!-- 禁用 恢复使用弹框 -->
        <el-dialog :title="dialogText" :visible.sync="dialogVisible" :close-on-click-modal="false" width="30%"
            @close="toCancel()">
            <div class="dialog_content">
                <p v-show="dialogText === $t('versionManagement.version48')">{{ $t('versionManagement.version49') }}</p>
                <p v-show="dialogText === $t('versionManagement.version53')">{{ $t('versionManagement.version54') }}</p>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="70px">
                    <el-form-item :label="$t('versionManagement.version50')" prop="reason">
                        <el-input v-show="dialogText === $t('versionManagement.version48')" minlength="0"
                            maxlength="100" type="textarea" :rows="3" :placeholder="$t('versionManagement.version51')"
                            show-word-limit v-model="ruleForm.reason">
                        </el-input>
                        <el-input v-show="dialogText === $t('versionManagement.version53')" minlength="0"
                            maxlength="100" type="textarea" :rows="3" :placeholder="$t('versionManagement.version55')"
                            show-word-limit v-model="ruleForm.reason">
                        </el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="toCancel()">
                    {{ $t('add.add31') }}
                </el-button>
                <el-button type="primary" @click="toSubmit()">
                    {{ $t('add.add30') }}
                </el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import waterTable from './waterTable.vue';
import Clipboard from 'clipboard';
export default {
    // eslint-disable-next-line vue/multi-word-component-names
    name: 'packageLink',

    data() {
        return {
            tableData: [],
            pageable: {
                total: 0,
                page: 1,
                pageSize: 10,
            },
            clientTypeOptions: [
                {
                    value: '9',
                    label: 'DentalScanner3.0',
                },
                {
                    value: '8',
                    label: 'DentalScanner2.0',
                },
                {
                    value: '2',
                    label: 'IntraoralScanner',
                },
                {
                    value: '4',
                    label: 'OrthoSimulator',
                },
                {
                    value: '6',
                    label: 'Splintdesign',
                },
                {
                    value: '7',
                    label: 'Crowndesign',
                },
            ],
            dialogVisible: false,
            dialogText: '',
            ruleForm: {
                reason: '',
            },
            rules: {

            },
            currRow: {},

            // 是否展示流水表
            isShowWaterTable: false,
            tableH: 570,

            addDialogVisible: false,

            addRuleForm: {
                clientType: '',
                version: '',
                url: '',
                versionType: ''
            },
            addRules: {
                clientType: [
                    { required: true, message: this.$t('versionManagement.version15'), trigger: 'change' },
                ],
                version: [
                    { required: true, message: this.$t('versionManagement.version11'), trigger: 'blur' },
                ],
                url: [
                    { required: true, message: this.$t('versionManagement.version57'), trigger: 'blur' },
                ],
            },
            clipboard: null,
        };
    },

    components: {
        waterTable
    },
    created() {
        this.getTableData();

        // 处理不同方法的客户端类型
        this.handleClientType();
    },
    mounted() {

    },
    methods: {
        handleClientType() {
            if (this.$config.type === 'currVersion') {
                this.clientTypeOptions = [
                    {
                        value: '9',
                        label: 'DentalScanner3.0',
                    },
                    {
                        value: '8',
                        label: 'DentalScanner2.0',
                    },
                    {
                        value: '2',
                        label: 'IntraoralScanner',
                    },
                    {
                        value: '4',
                        label: 'OrthoSimulator',
                    },
                    {
                        value: '6',
                        label: 'Splintdesign',
                    },
                    {
                        value: '7',
                        label: 'Crowndesign',
                    },
                ];
            } else {
                this.clientTypeOptions = [
                    {
                        value: '8',
                        label: 'DentalScanner2.0',
                    },
                    {
                        value: '2',
                        label: 'IntraoralScanner',
                    },
                    {
                        value: '3',
                        label: 'OrthoSimulator',
                    },
                    {
                        value: '6',
                        label: 'Splintdesign',
                    },
                    {
                        value: '7',
                        label: 'Crowndesign',
                    },
                ];
            }
        },
        onAdd() {
            this.addDialogVisible = true;
        },
        getTableData() {
            this.$http
                .get(`clientinstallationpackageinterface/page?page=${this.pageable.page}&limit=${this.pageable.pageSize}`)
                .then(({ data: res }) => {

                    if (res.code === 0 && res.data) {
                        const { list, total } = res.data;
                        this.tableData = list;
                        this.pageable.total = Number(total);

                    } else {

                        this.tableData = [];
                        this.pageable.total = 0;
                        this.pageable.page = 1;
                    }
                })
                .catch((e) => console.error(e));
        },
        onPageSizeChange(pageSize) {
            this.pageable.pageSize = pageSize;
            this.getTableData();
        },
        onPageChange(page) {
            this.pageable.page = page;
            this.getTableData();
        },
        getClientTypeLabel(value) {

            const index = this.clientTypeOptions.findIndex((e) => e.value === value);
            if (index !== -1) return this.clientTypeOptions[index].label;
            return '';
        },
        toAction(type, row) {
            this.currRow = row;

            if (type === '1') {
                if (this.clipboard) {
                    this.clipboard.destroy(); // 销毁之前的实例，避免多次绑定
                }
                // 临时创建一个隐藏按钮用于绑定 clipboard
                const tempButton = document.createElement("button");
                document.body.appendChild(tempButton);
                // 创建 clipboard 实例并绑定临时按钮
                this.clipboard = new Clipboard(tempButton, {
                    text: () => this.$config.downloadUrl + row.url,
                });

                // 监听成功事件
                this.clipboard.on("success", (e) => {
                    this.$message.success(this.$t('versionManagement.version61'));
                    this.clipboard.destroy(); // 复制完成后销毁实例
                    document.body.removeChild(tempButton); // 移除临时按钮
                });



                // 手动触发点击事件，执行复制
                tempButton.click();




            } else if (type === '2') {
                // 禁用
                this.dialogVisible = true;
                this.dialogText = this.$t('versionManagement.version48');
                this.rules = {
                    reason: [
                        { required: true, message: this.$t('versionManagement.version51'), trigger: 'blur' },
                    ],
                };
            } else if (type === '3') {
                // 恢复使用
                this.dialogVisible = true;
                this.dialogText = this.$t('versionManagement.version53');
                this.rules = {
                    reason: [
                        { required: true, message: this.$t('versionManagement.version55'), trigger: 'blur' },
                    ],
                };
            } else if (type === '4') {
                // 查看
                this.tableH = 270;

                this.isShowWaterTable = true;
            }
            this.$nextTick(() => {
                if (this.$refs['ruleForm']) {
                    this.$refs['ruleForm'].resetFields();
                }
            });

        },
        toMainCancel() {
            this.addDialogVisible = false;
            this.addRuleForm = {
                clientType: '',
                version: '',
                url: '',
            };
        },
        toMainSubmit() {
            let formData = {
                clientType: this.addRuleForm.clientType,
                version: this.addRuleForm.version,
                url: this.addRuleForm.url,
                versionType: this.addRuleForm.versionType,
            };
            this.$refs['addRuleForm'].validate((valid) => {
                if (valid) {
                    this.$http({
                        method: 'post',
                        url: `/clientinstallationpackageinterface/save`, //后端接口
                        data: formData,
                    }).then(({ data: res }) => {
                        if (res.code !== 0) {
                            return this.$message.error(res.data.msg);
                        } else {
                            this.addDialogVisible = false;
                            this.$message.success(this.$t('versionManagement.version25'));
                            this.getTableData();
                        }
                    });

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        toCancel() {



            this.dialogVisible = false;
            this.ruleForm = {
                reason: '',
            };



        },
        toSubmit() {
            let waterTableRef = this.$refs.waterTable;
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    let status = '';
                    if (this.dialogText === this.$t('versionManagement.version48')) {
                        status = '-1';
                    } else if (this.dialogText === this.$t('versionManagement.version53')) {
                        status = '1';
                    }
                    let formData = new FormData();
                    formData.append('id', this.currRow.id);
                    formData.append('reason', this.ruleForm.reason);
                    formData.append('status', status);

                    this.$http({
                        method: 'post',
                        url: `/clientinstallationpackageinterface/updateState`, //后端接口
                        data: formData,
                    }).then(({ data: res }) => {

                        if (res.code !== 0) {
                            return this.$message.error(res.data.msg);
                        } else {
                            if (status === '1') {
                                this.$message({
                                    message: this.$t('versionManagement.version56'),
                                    type: 'success',
                                });
                            } else if (status === '-1') {
                                this.$message({
                                    message: this.$t('versionManagement.version52'),
                                    type: 'success',
                                });
                            }
                            this.dialogVisible = false;
                            this.getTableData();
                            waterTableRef.toQuery();
                        }
                    });

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
    }
};
</script>

<style lang="scss" scoped>
.packageLink {
    width: 100%;
    height: 100%;

    .dialog_content {
        >p {
            margin-bottom: 20px;
            color: red;
            font-size: 16px;

        }

        ::v-deep .el-form-item__label {
            text-align: left;
        }
    }
}
</style>